package com.wangfugui.mybatisplus.utils;

import com.wangfugui.mybatisplus.domain.SecurityInfo;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

public class EastMoneyApiCrawler {

    public static void main(String[] args) {
        String stockCode = "AVGO"; // 示例股票代码，可以修改为其他代码
        SecurityInfo securityInfo = crawlStockInfo(stockCode);
        System.out.println(securityInfo);
    }
    public static SecurityInfo crawlStockInfo(String stockCode) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 第一步：获取公司基本信息
            String companyInfoUrl = "https://datacenter.eastmoney.com/securities/api/data/v1/get?reportName=RPT_USF10_INFO_ORGPROFILE&columns=SECUCODE%2CSECURITY_CODE%2CORG_CODE%2CSECURITY_INNER_CODE%2CORG_NAME%2CORG_EN_ABBR%2CBELONG_INDUSTRY%2CFOUND_DATE%2CCHAIRMAN%2CREG_PLACE%2CADDRESS%2CEMP_NUM%2CORG_TEL%2CORG_FAX%2CORG_EMAIL%2CORG_WEB%2CORG_PROFILE&quoteColumns=&filter=(SECURITY_CODE%3D%22"+stockCode+"%22)&pageNumber=1&pageSize=200&sortTypes=&sortColumns=&source=SECURITIES&client=PC&v=02648135848595099";

            String companyInfoJson = fetchData(httpClient, companyInfoUrl);
            JSONObject companyData = new JSONObject(companyInfoJson);
            
            // 解析公司信息
            JSONArray companyResults = companyData.getJSONObject("result").getJSONArray("data");
            if (companyResults.length() == 0) {
                System.out.println("未找到股票代码为 " + stockCode + " 的公司信息");
                return null;
            }

            JSONObject companyInfo = companyResults.getJSONObject(0);
            String secuCode = companyInfo.getString("SECUCODE");
            String orgEnAbbr = companyInfo.getString("ORG_EN_ABBR");
            String belongIndustry = companyInfo.getString("BELONG_INDUSTRY");

            System.out.println("股票代码: " + stockCode);
            System.out.println("公司英文简称: " + orgEnAbbr);
            System.out.println("所属行业: " + belongIndustry);
            System.out.println("SECUCODE: " + secuCode);
            SecurityInfo securityInfo = new SecurityInfo();
            securityInfo.setSecurityName(orgEnAbbr);
            securityInfo.setSector(belongIndustry);
            securityInfo.setCode(stockCode);
            // 第二步：使用SECUCODE获取证券信息
            String securityInfoUrl = "https://datacenter.eastmoney.com/securities/api/data/v1/get?reportName=RPT_USF10_INFO_SECURITYINFO&columns=SECUCODE%2CSECURITY_CODE%2CORG_CODE%2CSECURITY_INNER_CODE%2CSECURITY_TYPE%2CLISTING_DATE%2CISIN_CODE%2CTRADE_MARKET%2CYEAR_SETTLE_DAY%2CPAR_VALUE%2CCONVERT_RATIO%2CISSUE_PRICE%2CISSUE_NUM&quoteColumns=&filter=(SECUCODE%3D%22"+secuCode+"%22)&pageNumber=1&pageSize=200&sortTypes=&sortColumns=&source=SECURITIES&client=PC&v=08532229683738423";

            String securityInfoJson = fetchData(httpClient, securityInfoUrl);
            JSONObject securityData = new JSONObject(securityInfoJson);

            // 解析证券信息
            JSONArray securityResults = securityData.getJSONObject("result").getJSONArray("data");
            if (securityResults.length() > 0) {
                JSONObject jsonObject = securityResults.getJSONObject(0);
                String isinCode = jsonObject.getString("ISIN_CODE");
                String tradeMarket = jsonObject.getString("TRADE_MARKET");

                System.out.println("ISIN代码: " + isinCode);
                System.out.println("交易市场: " + tradeMarket);
                securityInfo.setIsin(isinCode);
                securityInfo.setExchangeName(tradeMarket);
                return securityInfo;
            } else {
                System.out.println("未找到SECUCODE为 " + secuCode + " 的证券信息");
            }

        } catch (Exception e) {
//            e.printStackTrace();
        }
        return null;
    }

    private static String fetchData(CloseableHttpClient httpClient, String url) throws Exception {
        HttpGet request = new HttpGet(url);
        request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        }
    }
}